
package com.netease.xone.view;

import media.MediaRecorderWrapper;
import media.MediaRecorderWrapper.MediaRecorderListener;
import Utils.StackTraceUtil;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.TextView;

import com.netease.log.NTLog;
import com.netease.xone.R;

public class DiscussRecorderView extends ImageView implements MediaRecorderListener {

    public static final String TAG = DiscussRecorderView.class.getSimpleName();

    private boolean bStart = false;
    private int mCX = 0;
    private int mCY = 0;
    // 刷新屏幕时间间隔
    private int mRefreshDuration = 20;
    // 圆形宽度
    private int mStrokeWidth;
    // 中间波形颜色
    private int mProgressFirstColor;
    // 圆形颜色
    private int mProgressSecondColor;
    private int mWaveTop;
    private int mWaveWidth;
    private int mWaveHeight;
    private int mRoundX;
    private int mRoundY;

    private int mAvg;
    private int mMin;
    private int mMax;
    private int mCount;
    private long mSum;

    // 语音强度
    private int mMaxAmplitude;

    private long mStartTime;
    // 录音时长
    private long mDuration = 90 * 1000;
    
    // 倒计时开始时间
    private long mRemain = 70 * 1000;

    private float mMaxDegree = 360f;
    // 当前角度
    private float mCurrentDegree;
    // 开始角度
    private float mStartDegree = -90f;
    private float mAlpha = 0.8f;

    private RectF mWaveRectF;
    private RectF mDrawArcRectF;
    private Paint mBoundFirstPaint;
    private Paint mBoundSecondPaint;

    private Drawable mRecorderShell;
    private Drawable mRecorderHighlight;
    // 倒计时显示
    private TextView mRemainTextView;

    public DiscussRecorderView(Context context) {
        this(context, null);
    }

    public DiscussRecorderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DiscussRecorderView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        mProgressFirstColor = getContext().getResources().getColor(R.color.discuss_recorder_color);
        mProgressSecondColor = getContext().getResources().getColor(R.color.discuss_recorder_color);
        mRecorderShell = getContext().getResources().getDrawable(R.drawable.btn_recorder_shell);
        mRecorderHighlight = getContext().getResources().getDrawable(R.drawable.btn_recorder_highlight);
        
        mStrokeWidth = getContext().getResources().getDimensionPixelSize(R.dimen.discuss_size_6);
        mWaveTop = getContext().getResources().getDimensionPixelSize(R.dimen.discuss_size_35);
        mWaveWidth = getContext().getResources().getDimensionPixelSize(R.dimen.discuss_size_24);
        mWaveHeight = getContext().getResources().getDimensionPixelSize(R.dimen.discuss_size_56);
        mRoundX = getContext().getResources().getDimensionPixelSize(R.dimen.discuss_size_10);
        mRoundY = mRoundX;

        mBoundFirstPaint = new Paint();
        mBoundFirstPaint.setAntiAlias(true);
        mBoundFirstPaint.setColor(mProgressFirstColor);
        mBoundFirstPaint.setStyle(Paint.Style.FILL);
        mBoundFirstPaint.setStrokeWidth(mStrokeWidth);

        mBoundSecondPaint = new Paint();
        mBoundSecondPaint.setAntiAlias(true);
        mBoundSecondPaint.setStyle(Paint.Style.STROKE);
        mBoundSecondPaint.setStrokeWidth(mStrokeWidth+2);
        mBoundSecondPaint.setColor(mProgressSecondColor);

        mWaveRectF = new RectF(0, 0, 0, 0);
        mDrawArcRectF = new RectF(0, 0, 0, 0);
    }

    public void start() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        bStart = true;
        mAvg = 0;
        mMax = 0;
        mMin = 65565;
        mCount = 0;
        mSum = 0;
        // 注册语音强度监听
        MediaRecorderWrapper.getInstance().setListener(this);
        mStartTime = System.currentTimeMillis();
        postDelayed(mRunnable, mRefreshDuration);
    }

    private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            long current = System.currentTimeMillis();
            long timeLapse = current - mStartTime;
            
            if (timeLapse > mRemain && null != mRemainTextView) {
                mRemainTextView.setText(String.valueOf((int)(mDuration-timeLapse)/1000));
            }
            
            mCurrentDegree = timeLapse * mMaxDegree / mDuration;
            if (timeLapse > mDuration) {
                // 模拟点击结束录音
                performClick();
                return;
            } else {
                postDelayed(mRunnable, mRefreshDuration);
                invalidate();
            }
        }

    };

    public void stop() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        // 取消语音强度监听
        MediaRecorderWrapper.getInstance().setListener(null);
        bStart = false;
        // 清空倒计时
        if (null != mRemainTextView) {
            mRemainTextView.setText(null);
        }
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " mAvg=" + mAvg + " mMax=" + mMax + " mMin="
                + mMin);
    }

    /**
     * 设置倒计时显示
     * @param tv
     */
    public void setRemain(TextView tv) {
        mRemainTextView = tv;
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int pL = getPaddingLeft();
        int pR = getPaddingRight();
        int pT = getPaddingTop();
        int pB = getPaddingBottom();

        mCX = (getMeasuredWidth()) / 2;
        mCY = (getMeasuredHeight()) / 2;

        mDrawArcRectF.set(0, 0, getMeasuredWidth() - pL - pR - 2 * mStrokeWidth, getMeasuredHeight() - pT - pB - 2 * mStrokeWidth);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Rect rect = getDrawable().getBounds();
        int alpha = (int)(mAlpha*255);
        
        canvas.save();
        if (bStart) {
            // 画波形
            int waveMid = mWaveTop + mWaveHeight / 2;
            int len = 0;
            if ((mMax-mAvg) != 0 && (mAvg - mMin) != 0) {
                if (mMaxAmplitude > mAvg) {
                    len = (mWaveHeight / 2) * (mMaxAmplitude - mAvg) / (mMax - mAvg);
                    waveMid = waveMid - len;
                } else {
                    len = (mWaveHeight / 2) * (mAvg - mMaxAmplitude) / (mAvg - mMin);
                    waveMid = waveMid + len;
                }
            }
            mWaveRectF.set(mCX - mWaveWidth / 2, waveMid, mCX + mWaveWidth / 2, mWaveTop + mWaveHeight);
            mBoundFirstPaint.setAlpha(alpha);
            canvas.drawRoundRect(mWaveRectF, mRoundX, mRoundY, mBoundFirstPaint);
        }

        mRecorderShell.setBounds(rect);
        mRecorderShell.draw(canvas);
        mRecorderHighlight.setBounds(rect);
        mRecorderHighlight.draw(canvas);
        canvas.restore();

        if (bStart) {
            // 画圈进度
            canvas.save();
            canvas.translate(getPaddingLeft() + mStrokeWidth, getPaddingTop() + mStrokeWidth);
            mBoundSecondPaint.setAlpha(alpha);
            canvas.drawArc(mDrawArcRectF, mStartDegree, mCurrentDegree, false, mBoundSecondPaint);
            canvas.restore();
        }
    }

    @Override
    public void onMaxAmplitude(int value) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " mMaxAmplitude=" + value);
        if (value > 0) {
            mMaxAmplitude = value;
            mSum += value;
            mCount++;
            if (value > mMax) {
                mMax = value;
            }

            if (mMin > value) {
                mMin = value;
            }
            mAvg = (int)mSum / mCount;
        }
    }
}
